package common;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;

import models.Article;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import play.cache.Cache;
import play.jobs.Job;

import sun.net.www.content.audio.wav;

public class ArticleReaderJob extends Job<Elements> {

	private String articleUrl;

	public ArticleReaderJob(String _articleUrl) {
		this.articleUrl = _articleUrl;
	}

	@Override
	public Elements doJobWithResult() throws Exception {

		Elements cleanArticle = null;
		String host = null;

		try {

			URL article = new URL(articleUrl);
			host = article.getHost();

			// Thread.sleep(Long.valueOf(sleepInterval));

			// socket timeout almamak için 10 sn delay verdim.
			Document articleWithJunk = Jsoup.connect(articleUrl)
					.timeout(10 * 1000).get();

			ArrayList<String> selectors = (ArrayList<String>) Cache.get(host);

			for (String string : selectors) {
				cleanArticle = articleWithJunk.select(string);
				if (!cleanArticle.isEmpty())
					break;
			}
		}

		catch (NullPointerException e) {
			System.out.println("Article Reader de Hata from " + host);
		}

		catch (SocketTimeoutException e) {
			System.out.println("------------------<HATA>------------");
			System.out.println("From " + articleUrl + " and hostUrl: " + host);
			System.out.println("------------------</HATA>------------");
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		
		return cleanArticle;
	}

	@Override
	public void doJob() throws Exception {

	}
}
